#include "Config.h"

bool Config::read(const string& file) {
	ifstream in;
	in.open(file.c_str());
	if(in.fail()) {
		cerr << "Open config file: " << file << " error" << endl;
		return false;
	}

	cout << "Load config file: " << file << endl;

	string line;
	while(!in.eof()) {
		getline(in, line);

		// ignore blank lines and comments
		if(line.empty() || line[0] == '#')
			continue;
		
		// under windows the line is end with \r\n
		line.erase(remove(line.begin(), line.end(), '\r'), line.end());
		line.erase(remove(line.begin(), line.end(), '\n'), line.end());

		string :: size_type split = line.find("=");

		if(split == string :: npos)
			continue;

		string :: size_type keyStart = line.find_first_not_of(" ");
		string :: size_type keyEnd = line.find(" ", keyStart);
		string :: size_type valueStart = line.find_first_not_of(" ", split + 1);
		string :: size_type valueEnd = line.size();

		if(valueStart != string :: npos)
			cfgs[line.substr(keyStart, keyEnd - keyStart)] = line.substr(valueStart, valueEnd - valueStart);
	}

	in.close();
	return true;
}

bool Config::hasKey(const string& key) const {
	return cfgs.find(key) != cfgs.end();
}

int Config::getInt(const string& key, int defVal) {
	if(!hasKey(key))
		return defVal;
	
	istringstream iss(cfgs[key]);
	iss >> defVal;
	return defVal;
}

string Config::getString(const string& key, const string& defVal) {
	if(!hasKey(key))
		return defVal;
	
	return cfgs[key];
}
